package com.lagou.rabbitmq.controller;

import com.lagou.rabbitmq.config.RabbitConfig;
import com.lagou.rabbitmq.model.Order;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName OrderController
 * @Description TODO
 * @Author xsq
 * @Date 2020/11/12 16:52
 **/
@Slf4j
@RestController
public class OrderController {

    @Autowired
    private AmqpTemplate rabbitTemplate;

    public static Map<Long,Order> orders = new ConcurrentHashMap<>(100);

    @PostMapping(value = "/order")
    public ResponseEntity order(){
        Order order = new Order();
        order.setOrderId(System.currentTimeMillis());
        order.setStatus("待支付");
        orders.put(order.getOrderId(),order);
        rabbitTemplate.convertAndSend(RabbitConfig.exchangeName, RabbitConfig.routeOrderName, order.getOrderId());
        return ResponseEntity.ok(order);
    }
    @PostMapping(value = "/pay")
    public ResponseEntity pay(long id){
        final Order order = orders.get(id);
        if (order.getStatus().equals("已过期")) {
            log.info("===========支付订单失败，订单已过期========== orderId="+id);
            return ResponseEntity.ok().body("支付失败，订单已过期");
        }
        log.info("===========支付订单成功========== orderId="+id);
        order.setStatus("已支付");
        return ResponseEntity.ok().body("支付成功");
    }

    @GetMapping(value = "/list")
    public ResponseEntity list(){
        return ResponseEntity.ok().body(orders.values());
    }
}
